import pandas as pd
import time

from django.conf import settings

from prj002.utils.constants import turn_to_chinese

from prj003.utils.constants import turn_to_chinese003
from prj004.utils.constants import turn_to_chinese004
from prj005.utils.constants import turn_to_chinese005

SAVE_EXCEL_PATH = settings.NGINX_EXCEL_PATH
SAVE_SERVER_PORT = ':'.join((settings.NGINX_SERVER, settings.NGINX_PORT))


def excel_instance(username, types=None, project_name=None, serial=None):
    if types:
        file_name = '{}-{}-{}.xlsx'.format(project_name, username, serial)
    else:
        file_name = '{}-{}.xlsx'.format(round(time.time()), username)

    writer = pd.ExcelWriter('{}{}'.format(SAVE_EXCEL_PATH, file_name), engine='xlsxwriter')
    df = pd.DataFrame()
    df.to_excel(writer, sheet_name='数据展示', index=False)
    wb = writer.book
    ws = writer.sheets['数据展示']
    # 内容写入表格
    # ws.write(0, 0, value)
    # 保存
    # writer.save()

    return ws, wb, writer, file_name


def create_excel(data, username, project_name, types=None, serial=None):
    """
    data: 数据形式
    [
        {
        'info': info-object,
        'summary': summary-object,
        ...
        },
        ...
    ]
    """
    ws, wb, writer, file_name = excel_instance(username, types=types, project_name=project_name, serial=serial)
    # 文档标题
    excel_title = {}
    title_index = 0
    content_index = 1

    if project_name == 'prj002':
        data_chinese = turn_to_chinese
    elif project_name == 'prj003':
        data_chinese = turn_to_chinese003
    elif project_name == 'prj004':
        data_chinese = turn_to_chinese004
    elif project_name == 'prj005':
        data_chinese = turn_to_chinese005
    else:
        raise ValueError('参数错误')

    for i, m in data_chinese.items():
        ws.write(0, title_index, m)
        excel_title.update({i: title_index})
        title_index += 1

    # 注释代码: 生成字段名对应的中文名称, 写入到json文件中
    # save_excel_object = {
    #     'info': info.Info,
    #     'clinical': clinical.Clinical,
    #     'cure': cure.Cure,
    #     'summary': summary.Summary,
    #     'history': history.History,
    # }
    # a = {}

    for instance in data:

        for k, v in instance.items():
            # 第一层 {'info': .., 'summary': ...}
            if v:
                for name, value in v.items():
                    idx = excel_title.get(name, 'no_index')
                    if idx == 'no_index':
                        continue

                    if isinstance(value, bool):
                        if value:
                            ws.write(content_index, idx, '是')
                        else:
                            ws.write(content_index, idx, '否')
                    else:
                        ws.write(content_index, idx, value)

                # for name, object_name in save_excel_object.items():
                #     if k == name and v is not None:
                #         for p, m in v.items():
                #             # 内层数据
                #             zh_hanz = object_name._meta.get_field(p).verbose_name
                #             a.update({p: zh_hanz})
        content_index += 1

    # with open('a.json', 'w') as file:
    #     file.write('{}'.format(a))

    writer.save()

    if not types:
        return '{}{}{}'.format(SAVE_SERVER_PORT, settings.NGINX_PATH, file_name)
